//登录和注册需要的User类
var User = require('../models/user');
//发表需要的Post类
var Post = require('../models/post');
//引入留言需要的Comment类
var Comment = require('../models/comment');
//需要引入一个加密的模块
var crypto = require('crypto');
//头像上传
var upload = require('../models/userpic');
//引入头像上传需要的multer插件
var multer = require('multer');

// var upload = multer({storage:storage,size:10225});


/* GET home page. */
//权限问题
//用户不登录的时候无法访问发表文章页面
//用户在登录的情况下 无法访问登录页面
//空用户名和密码的时候 判断
function checkLogin(req, res, next) {
    if (!req.session.user) {
        req.flash('error', '未登录！');
        res.redirect('/login');
    }
    next();
}
//如果上面的执行了就继续执行下面的 如果上面的没执行就执行其他的
//如果登录了 是无法访问登录和注册页面的 这只是用户名和密码都对的情况下
function checkNotLogin(req, res, next) {
    if (req.session.user) {
        req.flash('error', '已登录！');
        res.redirect('back');//返回之前页面
    }
    next();
}
module.exports = function (app) {
    app.get('/', function (req, res) {
        res.render('shouye');
    })

    //首页
    app.get('/shouye', function (req, res) {
        res.render('shouye')
    })
    //上传
    app.get('/upload', checkLogin);
    app.get('/upload', function (req, res) {
        res.render('upload', {
            title: '文件上传',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        })
    })
    //上传行为
    app.post('/upload', checkLogin);
    app.post('/upload', upload.array('field1', 5), function (req, res) {
        req.flash('success', '文件保存至public下的images文件夹中成功');
        res.redirect('/upload');
    })


    //个人简介
    app.get('/author', function (req, res) {
        res.render('author');
    })
    //个人相册
    app.get('/personnalphoto', function (req, res) {
        res.render('personnalphoto')
    })
//分页
    app.get('/personnal', function (req, res) {
        var page = parseInt(req.query.p) || 1;
        if (req.session.user) {
            // postName = req.session.user.name;
            picUrl = '/images/' + req.session.user.picUrl;
        }
        Post.getTen(null, page, function (err, posts, total) {
            if (err) {
                posts = [];
            }
            res.render('personnal', {
                title: '首页',
                user: req.session.user,
                page: page,
                posts: posts,
                isFirstPage: (page - 1) == 0,
                isLastPage: (page - 1) * 4 + posts.length == total,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()

            })
        })

    })
    //头像上传
    app.get('/userInfo', checkLogin, function (req, res) {
        res.render('userInfo', {
            title: '头像',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString(),
            photo: '/images/' + req.session.user.picUrl,
        })
    });

    //上传头像行为
    app.post('/userInfo', upload.single("photo"), function (req, res) {
        if (req.picUrl) {
            User.update(req.session.user.name, req.picUrl, function (err, user) {
                if (err) {
                    req.flash('err', '头像上传失败!');
                    res.redirect('/userInfo');
                }
                req.session.user = user;
                //头像上传成功后对post集合进行更新
                Post.updatePhoto(req.session.user.name, req.picUrl, function (err) {
                    if(err){
                        console.log('头像上传出现错误');
                    } else {
                        req.flash('success', '头像更换成功!');
                        res.redirect('/personnal');
                    }
                })

            });
        } else {
            res.end("请选择图片后上传");
        }
    });


    // ***************************
    //注册页面
    app.get('/zhuce', checkNotLogin);
    app.get('/zhuce', function (req, res) {
        res.render('zhuce', {
            title: '注册',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        })
    })
    //注册行为
    app.post('/zhuce', checkNotLogin);
    app.post('/zhuce', function (req, res) {
        //数据接收req.body
        //console.log(req.body);
        //验证用户名
        var rel = /^([a-z]|[A-Z])\w{5,9}$/;
        //验证密码
        var rel2 = /^\w{6,16}$/;
        //用户名
        var name = req.body.name;
        //密码
        var password = req.body.password;
        //确认密码
        var password_re = req.body['password-repeat'];
        //邮箱
        var email = req.body.email;
        //补充一下，如果未填写的情况下，提示用户
        if (name == '' || password == '' || password_re == '' || email == '') {
            req.flash('error', '请正确填写信息');
            return res.redirect('/zhuce');
        }
//关于注册的一些限制条件
        //用户名注册限制
        if (!rel.test(name)) {
            req.flash('error', '用户名条件不符合 请重新填写');
            return res.redirect('/zhuce')
        }
        //密码限制
        if (!rel2.test(password)) {
            req.flash('error', '密码格式不正确 请重新填写');
            return res.redirect('/zhuce')
        }


        //1.首先检查一下两次密码是否一样
        if (password_re != password) {
            //先保存一下当前的错误信息
            req.flash('error', '两次密码不一致 请重新输入');
            return res.redirect('/zhuce');
        }
        //2.对密码进行加密处理
        var md5 = crypto.createHash('md5');
        var password = md5.update(req.body.password).digest('hex');
        //console.log(password);

        //3.可以开始实例化User对象了
        var newUser = new User({
            name: name,
            password: password,
            email: email
        });
        //4.检查用户名是否存在
        User.get(newUser.name, function (err, user) {
            //如果发生了错误,跳转回首页
            if (err) {
                req.flash('error', err);
                return res.redirect('/shouye');
            }
            //如果存在重复的用户名
            if (user) {
                req.flash('error', '用户名已经存在');
                return res.redirect('/zhuce');
            }
            //正确情况下
            newUser.save(function (err, user) {
                if (err) {
                    req.flash('error', err);
                }
                //用户信息存入session
                req.session.user = newUser;
                //console.log(req.session.user);
                req.flash('success', '注册成功');
                res.redirect('/personnal');
            })
        })
    })
//登录
    app.get('/login', checkNotLogin);
    app.get('/login', function (req, res) {
        res.render('login', {
            title: '登录',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        })
    })
    //登录行为
    app.post('/login', checkNotLogin);
    app.post('/login', function (req, res) {
        //1.检查下用户名有没有
        //2.检查下密码对不对
        //3.存储到session中用户的登录信息
        //4.跳转到首页
        var md5 = crypto.createHash('md5');
        var password = md5.update(req.body.password).digest('hex');
        User.get(req.body.name, function (err, user) {
            if (!user) {
                //说明用户名不存在
                req.flash('error', '用户名不存在');
                return res.redirect('/login');
            }
            //检查两次密码是否一样
            if (user.password != password) {
                req.flash('error', '密码错误');
                return res.redirect('/login');
            }
            req.session.user = user;
            //console.log(req.session.user);
            req.flash('success', '登录成功');
            res.redirect('/personnal');
        })

    })

    //发表
    app.get('/post', checkLogin);
    app.get('/post', function (req, res) {
        res.render('post', {
            title: '发表',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        })
    })
    //发表行为
    app.post('/post', checkLogin);
    app.post('/post', function (req, res) {
        //当前SESSION里面的用户信息
        var currentUser = req.session.user;
        //判断一下内容不能为空
        if (req.body.title == '' || req.body.post == '') {
            req.flash('error', '内容不能为空');
            return res.redirect('/post');
        }
        //添加一下标签信息
        var tags = [req.body.tag1, req.body.tag2, req.body.tag3];
        var post = new Post(currentUser.name, req.body.title, tags, req.body.post,req.session.user.picUrl);
        post.save(function (err) {
            if (err) {
                req.flash('error', err);
                return res.redirect('/');
            }
            req.flash('success', '发布成功');
            res.redirect('/personnal');
        })
    })


    //点击用户名 可以看到用户发布的所有文章
    app.get('/u/:name', function (req, res) {
        var page = parseInt(req.query.p) || 1;
        var picUrl = '';
        if(req.session.user){
            picUrl = '/images/' + req.session.user.name;
        }
        //检查用户是否存在
        User.get(req.params.name, function (err, user) {
            if (!user) {
                req.flash('error', '用户不存在!');
                return res.redirect('/personnal');
            }
            //查询并返回该用户第 page 页的 10 篇文章
            Post.getTen(user.name, page, function (err, posts, total) {
                if (err) {
                    req.flash('error', err);
                    return res.redirect('/personnal');
                }
                res.render('user', {
                    title: user.name,
                    posts: posts,
                    page: page,
                    total:total,
                    isFirstPage: (page - 1) == 0,
                    isLastPage: ((page - 1) * 10 + posts.length) == total,
                    user: req.session.user,
                    success: req.flash('success').toString(),
                    error: req.flash('error').toString(),
                    photo:picUrl

                })
            })
        })
    })

    //文章详情页面
    app.get('/u/:name/:minute/:title', function (req, res) {
        Post.getOne(req.params.name, req.params.minute, req.params.title, function (err, post) {
            if (err) {
                req.flash('error', '找不到当前文章');
                return res.redirect('/');
            }
            res.render('article', {
                title: req.params.title,
                user: req.session.user,
                post: post,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            })
        })
    })

    //文章的留言发布
    app.post('/comment/:name/:minute/:title', function (req, res) {
        var date = new Date();
        var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +
            date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
        //接收表单里面传过来的数据 name time content内容
        var comment = {
            name: req.body.name,
            time: time,
            content: req.body.content
        }
        //?
        var newCommnet = new Comment(req.params.name, req.params.minute, req.params.title, comment);
        console.log(newCommnet);
        newCommnet.save(function (err) {
            if (err) {
                req.flash('error', err);
                return res.redirect('back');
            }
            req.flash('success', '发布成功');
            res.redirect('back');

        })
    })
    //文章编辑
    app.get('/edit/:name/:minute/:title', checkLogin);
    app.get('/edit/:name/:minute/:title', function (req, res) {
        //获取到当前的用户
        var currentUser = req.session.user;
        Post.edit(currentUser.name, req.params.minute, req.params.title, function (err, post) {
            if (err) {
                req.flash('error', err);
                return res.redirect('back');
            }
            res.render('edit', {
                title: '编辑文章',
                user: req.session.user,
                post: post,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            })
        })
    })
    //文章编辑行为
    app.post('/edit/:name/:minute/:title', checkLogin);
    app.post('/edit/:name/:minute/:title', function (req, res) {
        Post.update(req.params.name, req.params.minute, req.params.title,
            req.body.post, function (err) {
                //encodeURI是防止有中文的情况下，对中文的字符进行转义
                var url = encodeURI('/u/' + req.params.name + '/' + req.params.minute + '/' + req.params.title);
                if (err) {
                    req.flash('error', err);
                    return res.redirect(url);
                }
                req.flash('success', '编辑成功');
                return res.redirect('/personnal');
            })
    })

    //文章删除行为
    app.get('/remove/:name/:minute/:title', checkLogin);
    app.get('/remove/:name/:minute/:title', function (req, res) {
        Post.remove(req.params.name, req.params.minute, req.params.title, function (err) {
            if (err) {
                req.flash('error', err);
                return res.redirect('back');
            }
            req.flash('success', '修改成功');
            res.redirect('/personnal');
        })
    })

    //文章存档
    app.get('/archive', function (req, res) {
        Post.getArchive(function (err, posts) {
            if (err) {
                req.flash('error', err);
                return res.redirect('/');
            }
            res.render('archive', {
                title: '存档',
                posts: posts,
                user: req.session.user,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            })
        })
    })
    //文章标签页
    app.get('/tags', function (req, res) {
        Post.getTags(function (err, posts) {
            if (err) {
                req.flash('error', err);
                res.redirect('/');
            }
            res.render('tags', {
                title: '标签',
                posts: posts,
                user: req.session.user,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            })
        })
    })
    //标签对应的文章集合
    app.get('/tags/:tag', function (req, res) {
        Post.getTag(req.params.tag, function (err, posts) {
            if (err) {
                req.flash('error', err);
                return res.redirect('/tag');
            }
            res.render('tag', {
                title: 'TAG:' + req.params.tag,
                user: req.session.user,
                posts: posts,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            })
        })
    })
    //搜索
    app.get('/search', function (req, res) {
        Post.search(req.query.keyword, function (err, posts) {
            if (err) {
                req.flash('error', '不存在该文章');
                return res.redirect('/');
            }
            res.render('search', {
                title: 'SEARCH :' + req.query.keyword,
                user: req.session.user,
                posts: posts,
                success: req.flash('success').toString(),
                error: req.flash('error').toString()
            })
        })
    })
    //退出
    app.get('/logout', function (req, res) {
        //1.清除session
        //2.给用户提示
        //3.跳转到首页
        req.session.user = null;
        req.flash('success', '成功退出');
        res.redirect('/shouye');
    })
}





